<template>
	<view class="personal-info">
		<u-cell-group>
			<u-cell>
				<view slot="title" class="u-cell__title ">头像</view>
				<view slot="value">
					<!-- <u-avatar :src="userInfo.avatar" size="80rpx" /> -->
					<image @click="avatarimage" v-if="url_phoneimg != ''"
						src="https://jiangsudiantuo2022.oss-cn-hangzhou.aliyuncs.com/img/d486f37c1f8b7458c01bc2243e0333f252f2b33a.png"
						mode="" style="width: 30rpx; height: 30rpx;position: absolute;right: 16rpx;z-index: 999;">
					</image>
					<image style="width: 84rpx; height: 84rpx;" v-if="url_phoneimg != ''" :src="heading">
					</image>
					<u-upload v-else :fileList="fileList1" name="1" width="80rpx" height="80rpx" @afterRead="afterRead"
						@delete="deletePic" multiple :maxCount="1" />
				</view>
			</u-cell>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">名称</view>
					<input class='catname' type="text" v-model="ordersList.nickname" @input="nickInput"
						placeholder="请输入会员名称" />
				</view>
			</view>
			<view class='line'></view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title required">手机号</view>
					<input class='catname' type="text" v-model="ordersList.phone" @input="base_ageInput"
						placeholder="请输入手机号" />
				</view>
			</view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title required">真实姓名</view>
					<input class='catname' type="text" v-model="ordersList.username" @input="nameInput"
						placeholder="请输入真实姓名" />
				</view>
			</view>
			
			<view class='line'></view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">性别</view>
					<view style="margin-top: 36rpx;">
						<u-radio-group v-model="ordersList.insurance" @change="groupChange">
							<u-radio label="男" :name="1" />
							<u-radio label="女" :name="2" customStyle="margin-left: 60rpx;" />
						</u-radio-group>
					</view>
					<!-- <view class='catnames'>
						<view @click="showInsurancePicker = true" class="flex-between">
							<u-text :text="ordersList.insurance" v-if="ordersList.insurance" color="#999"></u-text>
							<u-text text="请选择" v-else color="#c0c4cc"></u-text>
						</view>
						<u-picker :show="showInsurancePicker" :columns="columns.insurance"
							@confirm="confirmPicker($event, 'insurance')" @cancel="showInsurancePicker = false" />
					</view> -->

				</view>
			</view>
			<view class='line'></view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">出生日期</view>
					<input class='catname' type="idcard" v-model="ordersList.birthday" disabled @click="showBirthdayPicker = true"
						placeholder="请输入出生日期" />
					
				</view>
			</view>
			<view class='line'></view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">所在城市</view>
					<input class='catname' type="idcard" v-model="ordersList.card_num"
						placeholder="请输入所在城市" />
				</view>
			</view>
			<view class='line'></view>

			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">身份证号</view>
					<input class='catname' type="idcard" v-model="ordersList.card_num"
						placeholder="请输入身份证号" />
				</view>
			</view>
			<view class='line'></view>
			
			<view class='ul'>
				<view class='li'>
					<view slot="title" class="u-cell__title">营销顾问</view>
					<input class='catname' type="idcard" v-model="ordersList.occupation_relation" disabled  @click="showoccupation = true"
						placeholder="请输入营销顾问" />
				</view>
			</view>
			<view class='line'></view>
			
		</u-cell-group>
		
		<!-- 生日 -->
		<u-datetime-picker v-model="defaultBirthday" :show="showBirthdayPicker" mode="date"
			:minDate="minDate" :maxDate="maxDate" @confirm="confirmBirthday"
			@cancel="showBirthdayPicker = false" />
		<!-- 营销顾问 -->
		<u-picker :show="showoccupation" :columns="occupation_status" keyName="label"
			@confirm="occupation_list" @cancel="showoccupation = false">
		</u-picker>
			
		<view class="btns flex-between">
			<u-button text="保存" shape="circle" color="linear-gradient(0deg, rgba(255,64,64,0.93), rgba(255,64,64,0.93), rgba(250,142,142,0.93));" @click="save"  size="large"></u-button>
		</view>
	</view>
</template>

<script>
	const venues = require("@/api/venues/venues.js");
	import {
		formatDate
	} from "@/utils/util.js";
	export default {
		data() {
			return {
				showInsurancePicker: false,
				userInfo: {
					avatar: '',
					nickname: '文若',
					name: '王越',
					phone: uni.getStorageSync('phone'),
					face: '',
					age: 28,
					height: '172cm',
					gender: '男',
					id: '',
				},
				isEdit: false,
				ordersList: {},
				xiugai: true,
				ordersList: {},
				base_height: '',
				base_sex: '',
				card_num: '',
				base_age: '',
				username: '',
				fileList1: [],
				url_phone: '',
				url_phoneimg: false,
				heading: '',
				columns: {
					insurance: [
						['男', '女']
					]
				},
				defaultBirthday: new Date(new Date().getFullYear() - 3, 0, 1).getTime(),
				showBirthdayPicker: false,
				minDate: new Date(new Date().getFullYear() - 100, 0, 1).getTime(),
				maxDate: Date.now(),
				showoccupation:false,
				occupation_status: [], //营销
			}
		},
		onLoad({
			edit = false
		}) {
			// if (uni.getStorageSync('headimg') != '') {
			// 	this.heading = uni.getStorageSync('headimg')
			// 	this.url_phoneimg = true
			// } 
			this.isEdit = !!edit;
			// this.getMyInfolist()
			this.xiugai = true
			this.conf()

		},
		methods: {
			async conf() {
				let occupation_list = [
					{
						id: 1,
						label: "袁教练"
					},
					{
						id: 2,
						label: "石教练"
					}
				]
				this.occupation_status.push(
					occupation_list
				)
				// let params = {
				// 	app_id: this.$https.weixinAppId,
				// 	project_id: getApp().globalData.projectId,
				// }
				// let res = await train.conf(params);
				// if (res.code == 1) {
					
				// 	this.occupation_status.push(
				// 		res.data.list.occupation_list
				// 	)
				// }
			},
			// 营销顾问
			occupation_list(e) {
				this.ordersList.occupation_relation = e.value[0].label
				this.ordersList.occupation_relation_id = e.value[0].id
				this.showoccupation = false
			},
			// 生日
			confirmBirthday({
				value
			}) {
				this.ordersList.birthday = formatDate(value, 'YYYY-MM-DD');
				this.showBirthdayPicker = false;
			},
			// 用户服务协议
			service() {
				uni.navigateTo({
					url: '/pages_other/agreement/agreement',
				})
			},
			// 隐私政策
			privacy() {
				uni.navigateTo({
					url: '/pages_other/privacy/privacy'
				})
			},
			// 服务协议
			agreement() {
				uni.navigateTo({
					url: '/pages_other/protocol/protocol',
				})
			},
			confirmPicker({
				value
			}, key) {
				this.ordersList[key] = value.join('');
				// if (this.formData[key] == '是') {
				// 	this.formData.insurance = 1
				// } else{
				// 	this.formData.insurance = 0
				// }
				this[`show${key[0].toUpperCase() + key.slice(1)}Picker`] = false;
			},
			avatarimage() {
				this.heading = ''
				// uni.removeStorageSync('headimg');
				this.url_phoneimg = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.url_phone
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://sass-test.doit10019.com/api/upload/uploadOneImage', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							// user: 'test',
							project_id: getApp().globalData.projectId,
							app_id: this.$https.weixinAppId,

						},
						success: (res) => {
							let result = JSON.parse(res.data);
							this.url_phone = result.data.url
							setTimeout(() => {
								resolve(this.url_phone)
							}, 1000)
						}
					});
				})
			},
			// 获取我的待付款订单
			async getMyInfolist() {
				uni.showLoading({
					title: "加载中...",
					mask: true,
				});
				let params = {
					appid: this.$https.weixinAppId,
					project_id: getApp().globalData.projectId,
					openid: uni.getStorageSync('openid'),
				};
				let res = await venues.getMyInfo(params);
				if (res.code === 1) {
					this.ordersList = res.data.data;
					this.ordersList.insurance = res.data.data.base_sex;
					if (res.data.data.headimg != '') {
						this.heading = res.data.data.headimg
						this.url_phoneimg = true
					}
					this.$nextTick(() => {
						uni.hideLoading();
					});
				}
			},
			// 人脸录入
			faceEntry() {
				if (!this.isEdit) return;
				uni.navigateTo({
					url: '/pages_a/face-entry/face-entry'
				});
			},
			// 编辑
			edit() {
				if (this.heading != '') {
					this.url_phone = this.heading
				}
				this.xiugai = false
				let param_na = {
					'nickname': this.ordersList.nickname,
					'phone': this.ordersList.phone,
					'base_height': this.ordersList.base_height,
					// 'base_sex': this.ordersList.base_sex,
					'base_sex': this.ordersList.insurance,
					'card_num': this.ordersList.card_num,
					'base_age': this.ordersList.base_age,
					'username': this.ordersList.username,
					'headimg': this.url_phone, //头像logo
				};
			},
			nameInput(e) {
				this.ordersList.username = e.detail.value
			},
			nickInput(e) {
				this.ordersList.nickname = e.detail.value
			},
			base_heightInput(e) {
				this.ordersList.base_height = e.detail.value
			},
			base_sexInput(e) {
				this.ordersList.base_sex = e.detail.value
			},
			card_numInput(e) {
				this.ordersList.card_num = e.detail.value
			},
			base_ageInput(e) {
				this.ordersList.base_age = e.detail.value
			},
			// 保存
			async save() {
				let that = this
				if (this.heading != '') {
					this.url_phone = this.heading
				}

				var code = that.ordersList.card_num
				if (!that.ordersList.card_num) { //判断如果身份证为空，提示用户输入身份证
					uni.showToast({
						title: '请输入身份证号码',
						icon: 'none'
					})
					return
				} else  { //判断身份证格式时候正确
					var ts = this;
					var code = that.ordersList.card_num
					//身份证号合法性验证
					//支持15位和18位身份证号
					//支持地址编码、出生日期、校验位验证
					var city = {
						11: "北京",
						12: "天津",
						13: "河北",
						14: "山西",
						15: "内蒙古",
						21: "辽宁",
						22: "吉林",
						23: "黑龙江 ",
						31: "上海",
						32: "江苏",
						33: "浙江",
						34: "安徽",
						35: "福建",
						36: "江西",
						37: "山东",
						41: "河南",
						42: "湖北 ",
						43: "湖南",
						44: "广东",
						45: "广西",
						46: "海南",
						50: "重庆",
						51: "四川",
						52: "贵州",
						53: "云南",
						54: "西藏 ",
						61: "陕西",
						62: "甘肃",
						63: "青海",
						64: "宁夏",
						65: "新疆",
						71: "台湾",
						81: "香港",
						82: "澳门",
						91: "国外 "
					};
					var tip = "";
					var pass = true;
					var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
					if (!code || !code.match(reg)) {
						tip = "身份证号格式错误";
						pass = false;
					} else if (!city[code.substr(0, 2)]) {
						tip = "地址编码错误";
						pass = false;
					} else {
						//18位身份证需要验证最后一位校验位
						if (code.length == 18) {
							code = code.split('');
							//∑(ai×Wi)(mod 11)
							//加权因子
							var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
							//校验位
							var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
							var sum = 0;
							var ai = 0;
							var wi = 0;
							for (var i = 0; i < 17; i++) {
								ai = code[i];
								wi = factor[i];
								sum += ai * wi;
							}
							var last = parity[sum % 11];
							if (parity[sum % 11] != code[17]) {
								tip = "校验位错误";
								pass = false;
							}
						}
					}
					if (!pass) {
						uni.showToast({
							title: '请输入正确身份证号码',
							icon: 'none'
						})
						return
					}
					// if (!pass) console.log("tip" + tip);
					// return pass;
				}
				let param_na = {
					'nickname': this.ordersList.nickname,
					'phone': this.ordersList.phone,
					'base_height': this.ordersList.base_height,
					// 'base_sex': this.ordersList.base_sex,
					'base_sex': this.ordersList.insurance,
					'card_num': this.ordersList.card_num,
					'base_age': this.ordersList.base_age,
					'username': this.ordersList.username,
					'headimg': this.url_phone, //头像logo
				};

				let params = {
					user_info: JSON.stringify(param_na),
					appid: this.$https.weixinAppId,
					project_id: getApp().globalData.projectId,
					openid: uni.getStorageSync('openid'),
				};
				console.log(JSON.stringify(params), '2222')
				let res = await venues.editUserInfo(params);
				if (res.code === 1) {
					// uni.setStorageSync('headimg', this.url_phone); 
					uni.setStorageSync('username', this.ordersList.username)
					uni.setStorageSync('is_sure', res.data.is_sure)
					let username = this.ordersList.username
					this.xiugai = true
					if (uni.getStorageSync('is_sure') == 1) {
						uni.navigateBack({
							delta: 1, //返回层数，2则上上页
						})
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.personal-info {
		background-color: #f7f7f7;
		min-height: 100vh;
		padding-bottom: calc(190rpx + env(safe-area-inset-bottom));

		/deep/.u-cell-group {
			background-color: #fff;
			flex-grow: 0;

			.u-cell-group__wrapper>.u-line {
				display: none;
			}

			.u-cell__body {
				padding: 0 18rpx 0 32rpx;
				height: 110rpx;
			}

			.u-cell__title {
				color: #333;
				font-size: 32rpx !important;
				font-weight: 500;

				&.required {
					&::before {
						content: '*';
						color: #fb2222;
					}
				}
			}

			.u-cell__value {
				color: #999;
			}
		}

		.btns {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			padding: 30rpx;
			padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

			/deep/.u-button {
				&+.u-button {
					margin-left: 20rpx;
					
				}
			}
		}

		.wrap {
			overflow: hidden;
		}

		.ul {
			width: 92%;
			height: 110rpx;
			margin: auto;
		}

		.li {
			width: 100%;
			height: 110rpx;
			line-height: 110rpx;
			display: flex;
			justify-content: space-between;
		}


		.li .left {
			font-size: 32rpx;
			color: #333;
			text-align: left;
		}


		.catname {
			color: #999;
			margin-left: 10rpx;
			margin-top: 40rpx;
			font-size: 26rpx;
		}

		.catnames {
			color: #999 !important;
			font-size: 26rpx;
		}

		input {
			text-align: right;
		}

		.line {
			width: 100%;
			height: 1rpx;
			background-color: #e6e6e6
		}



	}
</style>